<?php
/**
 * LICENSE
 * 
 * [license information]
 * 
 * @category   Nine
 * @copyright  Copyright (c) 2009 visualidea.org
 * @license    http://license.visualidea.org
 * @version    v 1.0 2009-04-15
 */
require_once 'Nine/Model.php';
class Models_Product extends Nine_Model
{ 
    /**
     * The primary key column or columns.
     * A compound key should be declared as an array.
     * You may declare a single-column primary key
     * as a string.
     *
     * @var mixed
     */
    protected $_primary = 'product_id';
    /**
     * The field name what we use to group all language rows together
     * 
     * @var string
     */
    protected $_groupField = 'product_gid';
    /**
     * Let system know this is miltilingual table or not.
     * If this table has multilingual fields, Zend_Db_Table_Select object
     * will be inserted language condition automatically.
     * 
     * @var array
     */
    protected $_multilingualFields = array('title', 'alias', 'intro_text', 'full_text', 'hit', 
                                           'last_view_date', 'meta_keywords', 'meta_description', 'enabled','price','price_extension');
    
    /**
     * Constructor.
     *
     * Supported params for $config are:
     * - db              = user-supplied instance of database connector,
     *                     or key name of registry instance.
     * - name            = table name.
     * - primary         = string or array of primary key(s).
     * - rowClass        = row class name.
     * - rowsetClass     = rowset class name.
     * - referenceMap    = array structure to declare relationship
     *                     to parent tables.
     * - dependentTables = array of child tables.
     * - metadataCache   = cache for information from adapter describeTable().
     *
     * @param  mixed $config Array of user-specified config options, or just the Db Adapter.
     * @return void
     */
    public function __construct($config = array())
    {
        $this->_name = $this->_prefix . 'product';
        return parent::__construct($config); 
    }

    /**
     * Get all product with conditions
     * 
     * @param $condition
     * @param $order
     * @param $count
     * @param $offset
     */
    public function getAllProducts($condition = array(), $order = null, $count = null, $offset = null)
    {
        $select = $this->select()
                ->setIntegrityCheck(false)
                ->from(array('c' => $this->_name))
                ->join(array('cc' => $this->_prefix . 'product_category'), 'c.product_category_gid = cc.product_category_gid', array('cname' => 'name'))
                ->join(array('l' => $this->_prefix . 'lang'), 'c.lang_id = l.lang_id', array('lname' => 'name', 'lang_image'))
                ->where('cc.lang_id=?', Nine_Language::getCurrentLangId())
                ->order($order)
                ->limit($count, $offset);
        /**
         * Conditions
         */
        if (null != @$condition['keyword']) {
            $sql = "SELECT product_gid FROM {$this->_name} WHERE " . $this->getAdapter()->quoteInto('title LIKE ?', "%{$condition['keyword']}%");
            $ids = $this->_db->fetchAll($sql);
            if (empty($ids)) {
                return array();
            }
            $idString = '';
            foreach ($ids as $row) {
                $idString .= $row['product_gid'] . ',';
            }
            /**
             * Add to select object
             */
            $select->where('c.product_gid IN (' . trim($idString, ',') .')');
        }
        if (null != @$condition['product_category_gid']) {
        	
        	$sql = "SELECT gid_string FROM {$this->_prefix}" . 'product_category' . " WHERE " . $this->getAdapter()->quoteInto('product_category_gid = ? ', $condition['product_category_gid']);
        	$ids = @reset($this->_db->fetchAll($sql));
            if (null == $ids) {
                $ids = '0';
            }
            /**
             * Add to select object
             */
            $select->where('c.product_category_gid IN (' . trim($ids['gid_string'], ',') .')');
        }
        
        return $this->fetchAll($select)->toArray();
    }
    
    public function getAllEnabledProductsByCategory( $catGid, $order = null, $count = null, $offset = null)
    {
    	require_once 'modules/product/models/ProductCategory.php';
    	$objCat = new Models_ProductCategory();
    	
    	$cat = @reset($objCat->getByColumns(array('product_category_gid=?' => $catGid))->toArray());
    	
    	$gidStr = @trim($cat['gid_string'].',0',','); 
    	/**
    	 * Get all enabled categories
    	 */
    	$select = $this->select()
                ->setIntegrityCheck(false)
                ->from(array('pc' => $this->_prefix . 'product_category'), array('product_category_gid'))
                ->where('pc.enabled = 1 AND pc.genabled = 1 AND pc.parent_genabled = 1')
                ->where('pc.product_category_gid IN (' . $gidStr .')');
                
        $cats   = $this->fetchAll($select)->toArray();
        $gidStr = '';
        foreach ($cats as $cat) {
        	$gidStr .= $cat['product_category_gid'] . ',';
        }
        $gidStr = @trim($gidStr.'0',',');
    	
        /**
         * Get all enabled products in enabled categories
         */
    	$select = $this->select()
                ->where('enabled = 1 AND genabled = 1')
                ->where('product_category_gid IN (' . $gidStr .')')
                ->order($order)
                ->limit($count, $offset);
                
    	return $this->fetchAll($select)->toArray();
    }
//  add more ==============================================================

    
 public function getAllEnabledProductsByCategoryOther( $catGid,$condition = array() ,$order = null, $count = null, $offset = null)
    {
    	require_once 'modules/product/models/ProductCategory.php';
    	$objCat = new Models_ProductCategory();
    	
    	$cat = @reset($objCat->getByColumns(array('product_category_gid=?' => $catGid))->toArray());
    	
    	$gidStr = @trim($cat['gid_string'].',0',','); 
    	/**
    	 * Get all enabled categories
    	 */
    	$select = $this->select()
                ->setIntegrityCheck(false)
                ->from(array('pc' => $this->_prefix . 'product_category'), array('product_category_gid'))
                ->where('pc.enabled = 1 AND pc.genabled = 1 AND pc.parent_genabled = 1')
                ->where('pc.product_category_gid IN (' . $gidStr .')');
                
        $cats   = $this->fetchAll($select)->toArray();
        $gidStr = '';
        foreach ($cats as $cat) {
        	$gidStr .= $cat['product_category_gid'] . ',';
        }
        $gidStr = @trim($gidStr.'0',',');
    	
        /**
         * Get all enabled products in enabled categories
         */
    	$select = $this->select()
                ->where('enabled = 1 AND genabled = 1')
                ->where('product_category_gid IN (' . $gidStr .')')
                ->order($order)
                ->limit($count, $offset);
    	 /**
          * Condition
          */       
         if (null != @$condition['exclude_product_gids']) {
         	$gidStr = trim($condition['exclude_product_gids'].',0',',');
         	$select->where('product_gid NOT IN (' . $gidStr .')');
         }       
    	return $this->fetchAll($select)->toArray();
    }
//=============================================================== 
    
    public function getProductById( $gid ) 
    {
    	$select = $this->select()
    			->where('product_gid=?',$gid);
    	
    	return @reset($this->fetchAll($select)->toArray());
    }
    
    
    public function increaseSorting($startPos = 1, $num = 1)
    {
        $sql = "UPDATE {$this->_name} SET sorting = sorting + " . intval($num) . " WHERE sorting >= " . intval($startPos);
        
        $this->_db->query($sql);
    }
    
    public function makeUpPrice( $_ )
    {
    	return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1.' , strrev( $_ ) ) );
    }
    
}